// component/buyPop/buyPop.js
const app = getApp(),
    globalData = app.globalData,
    api = require('../../api/index'),
    utils = require('../../utils/util.js');
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        pageData: { // 商品信息
            type: Object,
            value: {}
        },
        isGroup: {
            type: Boolean,
            value: false
        },
        groupId: {
            type: String,
            value: ''
        },
        isAdd: { // 是否是加入购物车
            type: Boolean,
            value: false
        },
        onum: {
            type: Number,
            value: 1
        }
    },

    attached() {
        this.getActive()
    },

    observers: {
        "pageData": function (newV, oldV) {
            if (newV) {
                console.log(newV, 'pagedata')
                this.getActive()
                // this.getMemberType()
            }
        },
        "isGroup": function (newV, oldV) {
            if (newV == true) {
                this.setData({
                    _isGroup: true
                })
            } else {
                this.setData({
                    _isGroup: false
                })
            }
            console.log(newV, 'isGroup', this.data._isGroup)
        },
        "groupId": function (newV, oldV) {
            if (newV) {
                this.setData({
                    _groupId: newV
                })
            } else {
                this.setData({
                    _groupId: ''
                })
            }
            console.log(newV, 'groupId', this.data._groupId)
        },
        "isAdd": function (newV, oldV) {
            console.log(newV,'isadd newv')
            if (newV) {
                this.setData({
                    _isAdd: true
                })
            } else {
                this.setData({
                    _isAdd: false
                })
            }
            console.log(newV, '_isAdd', this.data._isAdd)
        },
        "onum": function(newV, oldV){
            console.log(newV,'onum')
            if(newV){
                this.setData({
                    num: 1
                })
            }
        }

    },

    /**
     * 组件的初始数据
     */
    data: {
        showBuy: false,
        toast: {
            visible: false,
            text: ''
        },
        num: 1,
        imageBaseUri: globalData.imageBaseUri,
        active: 0,
        memberType: 0,
        isIpx: globalData.isIpx,
        _isGroup: false,
        _groupId: '',
        _isAdd: false
    },

    /**
     * 组件的方法列表
     */
    methods: {
        openPop() {
            this.setData({
                showBuy: true
            })
        },
        closePop() {
            this.setData({
                // showBuy: false,
                // num: 1
            })
            this.triggerEvent('closeSpec')
        },
        toSuerUser() {
            wx.navigateTo({
                url: '/pages/member/index/index',
            })
        },
        // 选择规格
        chooseSpec(e) {
            let item = e.currentTarget.dataset.item,
                index = e.currentTarget.dataset.index;

            this.setData({
                active: index
            })
        },
        subOne(e) {
            if (this.data.num <= 1) {
                this.setData({
                    toast: {
                        visible: true,
                        text: '不能少于一件哦'
                    },
                    num: 1
                })
            } else {
                this.setData({
                    num: this.data.num - 1,
                })
            }

        },

        addOne() {
            let specs = this.data.pageData.GoodsSpecDtos || [];
            if (this.data.num > specs[this.data.active].Stock) {
                this.setData({
                    num: specs[this.data.active].Stock,
                    toast: {
                        visible: true,
                        text: '已经超过库存数量'
                    },
                })
            } else {
                this.setData({
                    num: this.data.num + 1
                })
            }

        },
        // 去确认订单
        async toPay() {
            console.log(this.data.pageData, 'pagedata')
            let specs = this.data.pageData.GoodsSpecDtos || [];
            // hosInfo = this.data.hospitalInfo || {};

            if (!specs[this.data.active].Id) {
                this.setData({
                    toast: {
                        visible: true,
                        text: '操作频繁，请稍后再试'
                    },
                })
                return
            }

            if (this.data.pageData.GoodsSeckillDto && this.data.pageData.GoodsSeckillDto.Id) {
                specs[this.data.active].seckillId = this.data.pageData.GoodsSeckillDto.Id
            }

            let obj = {
                count: this.data.num,
                title: this.data.pageData.Title,
                spec: specs[this.data.active],
                imgUrl: this.data.pageData.GoodsFileDtos[0].FilePath || '',
                type: this.data.pageData.Type,
                isGroup: this.data._isGroup
            }
            // specs[this.data.active].FilePath = this.data.pageData.GoodsFileDtos[this.data.active].FilePath;

            let goods = encodeURIComponent(JSON.stringify([obj]));

            wx.navigateTo({
                url: `/pages/product/confirm/confirm?goods=${goods}&from=1&group=${this.data._isGroup}&groupId=${this.data._groupId}`
            })

            this.closePop()
        },

        // 加入购物车
        async addToCar() {
            if (!utils.getLoginState()) {
                return utils.checkLoginState({
                    routeUri: 3,
                    uri: `/pages/product/detail/detail?id=${this.data.id}&userId=${this.data.userId}`
                });
            }
            let spec = this.data.pageData.GoodsSpecDtos,
                arr = [],
                obj = {
                    goodsSpecId: spec[this.data.active].Id,
                    userId: wx.getStorageSync('userinfo').UserId || '',
                    goodsId: spec[this.data.active].GoodsId,
                    num: this.data.num
                }

            // if (wx.getStorageSync('cart')) {
            //     let storageCart = wx.getStorageSync('cart');
            //     arr = storageCart.push(obj);
            //     wx.setStorageSync('cart', arr);
            //     console.log(spec, 'spec', storageCart, arr)
            // } else {
            //     arr = arr.push(obj)
            //     wx.setStorageSync('cart', arr)
            // }

            arr.push(obj)

            try {
                let res = await api.cart.addCart(arr),
                    data = res.data.ResData || {};
                console.log(res, '添加购物车');
                this.setData({
                    toast: {
                        visible: true,
                        text: '加入购物车成功'
                    },
                    status: 2
                })
                // this.getCartList();
            } catch (e) {
                console.log(e, '添加购物车失败');
                this.setData({
                    toast: {
                        visible: true,
                        text: '加入购物车失败'
                    }
                })
            }
        },
        editNum(e) {
            console.log(this.data.num, 'num', e)
            let num = e.detail.value;
            this.setData({
                num
            })
        },

        checkNum(e) {
            let num = e.detail.value;
            this.verifyNum(num)
        },

        verifyNum(inputNum) {
            let num = inputNum;
            let specs = this.data.pageData.GoodsSpecDtos || [];
            if (num < 1) {
                num = 1;
                this.setData({
                    num,
                    toast: {
                        visible: true,
                        text: '不能少于一件哦'
                    },
                })
                return false
            } else if (num > specs[this.data.active].Stock) {
                num = specs[this.data.active].Stock
                this.setData({
                    num,
                    toast: {
                        visible: true,
                        text: '已经超过库存数量'
                    },
                })
                console.log(specs[this.data.active].Stock, 'specs[this.data.active].Stock')
                return false
            }

        },

        // 获取第一个不为0的规格index
        getActive() {
            let specs = this.data.pageData ? this.data.pageData.GoodsSpecDtos : [];
            if (specs) {
                for (let i = 0; i < specs.length; i++) {
                    if (specs[i].stock != 0) {
                        this.setData({
                            active: i
                        });
                        break;
                    }
                }
            }
        },

        // 获取会员类型
        getMemberType() {
            let memberType = wx.getStorageSync('memberType') || 0
            this.setData({
                memberType
            })
        },


    },

})
